<?php
/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/**
 * Paginates results.
 */
class paginate
{
	/**
	 * Creates link to the first page.
	 * 
	 * @return string
	 * @param $data ArrayObject[optional]
	 * @param $base_link String
	 * @param $text String[optional]
	 * @param $params Array[optional]
	 */
	static function first(ArrayObject $data, $base_link, $text=null, array $params=null)
	{
		if (empty($text)) {
			$text = t('First', 'global.paginate');
		}
		if (!isset($params)) {
			$params = array();
		}
		
		if ($data->page > 1)
		{
			unset($params['page']);
			return html::link($text, $base_link.'?'.implode_with_keys('&', '=', $params));
		}
		return '<span>'.$text.'</span>';
	}
	
	/**
	 * Creates link to the previous page.
	 * 
	 * @return string
	 * @param $data ArrayObject[optional]
	 * @param $base_link String
	 * @param $text String[optional]
	 * @param $params Array[optional]
	 */
	static function previous(ArrayObject $data, $base_link, $text=null, array $params=null)
	{
		if (empty($text)) {
			$text = t('Previous', 'global.paginate');
		}
		if (!isset($params)) {
			$params = array();
		}
		
		if ($data->page > 1)
		{
			unset($params['page']);
			if ($data->page > 2) {
				$params['page'] = ($data->page - 1);
			}
			return html::link($text, $base_link.'?'.implode_with_keys('&', '=', $params));
		}
		return '<span>'.$text.'</span>';
	}
	
	/**
	 * Creates link to the next page.
	 * 
	 * @return string
	 * @param $data ArrayObject[optional]
	 * @param $base_link String
	 * @param $text String[optional]
	 * @param $params Array[optional]
	 */
	static function next(ArrayObject $data, $base_link, $text=null, array $params=null)
	{
		if (empty($text)) {
			$text = t('Next', 'global.paginate');
		}
		if (!isset($params)) {
			$params = array();
		}
		$last_page = ceil((float)$data->count / $data->limit);
		
		if ((int)$data->page < $last_page)
		{
			$params['page'] = ($data->page + 1);
			return html::link($text, $base_link.'?'.implode_with_keys('&', '=', $params));
		}
		return '<span>'.$text.'</span>';
	}
	
	/**
	 * Creates link to the last page.
	 * 
	 * @return string
	 * @param $data ArrayObject[optional]
	 * @param $base_link String
	 * @param $text String[optional]
	 * @param $params Array[optional]
	 */
	static function last(ArrayObject $data, $base_link, $text=null, array $params=null)
	{
		if (empty($text)) {
			$text = t('Last', 'global.paginate');
		}
		if (!isset($params)) {
			$params = array();
		}
		$last_page = ceil((float)$data->count / $data->limit);
		
		if ($data->page < $last_page)
		{
			$params['page'] = ($last_page);
			return html::link($text, $base_link.'?'.implode_with_keys('&', '=', $params));
		}
		return '<span>'.$text.'</span>';
	}
}
?>